<template>
  <el-breadcrumb class="flex-y-c">
    <transition-group enter-active-class="animate__animated animate__fadeInRight">
      <el-breadcrumb-item v-for="(item, index) in breadcrumbs" :key="item.path">
        <span v-if="!item.redirect || index === breadcrumbs.length - 1">
          {{ item.meta.title }}
        </span>
        <a v-else @click.prevent="handleLink(item)">
          {{ item.meta.title }}
        </a>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script lang="ts" setup>
import { RouteLocationMatched } from 'vue-router'
import { compile } from 'path-to-regexp'
import router from '@/router'

const currentRoute = useRoute()

const breadcrumbs = ref<RouteLocationMatched[]>([])

watch(
  () => currentRoute.path,
  path => {
    if (path.startsWith('/redirect/')) {
      return
    }
    getBreadcrumb()
  }
)

onBeforeMount(() => {
  getBreadcrumb()
})

function getBreadcrumb() {
  // const matched = currentRoute.matched.filter(item => item.meta && item.meta.title)
  // if (!isDashboard(matched[0])) {
  //   matched = [{ path: '/home', meta: { title: '首页' } } as any].concat(matched)
  // }
  // breadcrumbs.value = matched.filter(item => {
  //   return item.meta && item.meta.title && item.meta.breadcrumb !== false
  // })
  breadcrumbs.value = currentRoute.matched.filter(item => {
    // item.children.length !== 1  当只有一个子菜单并且没有始终显示，就不显示当前菜单名称
    if (item.children.length === 1) {
      return item.meta && item.meta.title && item.meta.breadcrumb !== false && item.meta.alwaysShow === true
    }
    return item.meta && item.meta.title && item.meta.breadcrumb !== false
  })
}

// function isDashboard(route: RouteLocationMatched) {
//   const name = route && route.name
//   if (!name) {
//     return false
//   }
//   return name.toString().trim().toLocaleLowerCase() === 'Home'.toLocaleLowerCase()
// }

function handleLink(item: any) {
  const { redirect, path } = item
  if (redirect) {
    router.push(redirect).catch(err => {
      console.warn(err)
    })
    return
  }
  router.push(pathCompile(path)).catch(err => {
    console.warn(err)
  })
}

// const toPath = compile("/user/:id")
// toPath({ id: "name" }) => "/user/name"
const pathCompile = (path: string) => {
  const { params } = currentRoute
  const toPath = compile(path)
  return toPath(params)
}
</script>
<style lang="scss" scoped>
// 覆盖 element-plus 的样式
.el-breadcrumb__inner,
.el-breadcrumb__inner a {
  font-weight: 400 !important;
}
</style>
